package com.sj.uabrowser.mvp.main.presenter;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.orhanobut.logger.Logger;
import com.sj.uabrowser.app.AESCrypt;
import com.sj.uabrowser.app.SPUtil;
import com.sj.uabrowser.app.TApp;
import com.sj.uabrowser.framework.BasePresenter;
import com.sj.uabrowser.mvp.main.bean.HomeTab;
import com.sj.uabrowser.mvp.main.bean.HomeTabs;
import com.sj.uabrowser.mvp.main.bean.MainNewFuncs;
import com.sj.uabrowser.mvp.main.bean.PageBean;
import com.sj.uabrowser.mvp.main.contract.MainContract;
import com.sj.uabrowser.mvp.main.loader.FuncsLoader;
import com.sj.uabrowser.mvp.main.loader.NewsLoader;
import com.sj.uabrowser.mvp.wea.bean.LocationCity;
import com.sj.uabrowser.mvp.wea.bean.MainContent;
import com.sj.uabrowser.mvp.wea.bean.MainContentBean;
import com.sj.uabrowser.mvp.wea.bean.SearchCity;
import com.sj.uabrowser.mvp.wea.loader.CityLoader;
import com.sj.uabrowser.mvp.wea.loader.MainLoader;
import com.sj.uabrowser.net.bean.MainFunc;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;

import javax.crypto.spec.SecretKeySpec;

import okhttp3.ResponseBody;

public class MainPresenter implements MainContract.Presenter {

    public static String sKey = "2345android_key_";
    public static String ivParameter = "2345tqIv_shiqing";

    private MainContract.View mView;
    private NewsLoader newsLoader;
    private FuncsLoader funcsLoader;

    private MainLoader mainLoader;
    private CityLoader cityLoader;

    public MainPresenter(MainContract.View mView) {
        newsLoader = new NewsLoader(this);
        funcsLoader = new FuncsLoader(this);
        mainLoader = new MainLoader(this);
        cityLoader = new CityLoader(this);
        this.mView = mView;
    }

    @Override
    public void fetchNewsTab(TreeMap<String, Object> params) {
        if (newsLoader != null) newsLoader.fetchNewsTab(0, params);
    }

    @Override
    public void fetchFuncs(TreeMap<String, Object> params) {
        if (funcsLoader != null) funcsLoader.requestFuncs(1, params);
    }

    @Override
    public void fetchCityId(String province,String cityname,String area) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("province", province);
        params.put("city",cityname);
        params.put("area",area);
        if (cityLoader != null) cityLoader.fetchCityId(3, params);
    }

    @Override
    public void fetchMainContent(String id) {
        if (mainLoader != null) mainLoader.mainInfo2(2, id);
    }

    @Override
    public void onDataCallBack(int requestId, Object data) {
        if (mView == null) return;
        Gson gson = new GsonBuilder().create();
        switch (requestId) {
            case 0:
                PageBean<HomeTab> homeTabs = (PageBean<HomeTab>) data;
                String hometabsStr = gson.toJson(homeTabs);
                SPUtil.put(TApp.getInstance().getApplicationContext(),"homeTabsStr",hometabsStr);
                if (homeTabs != null) {
                    mView.showNewsTab(homeTabs.getData());
                }
                break;
            case 1:
                MainNewFuncs mainNewFuncs = (MainNewFuncs) data;
                String mainFuncString = gson.toJson(mainNewFuncs);
                SPUtil.put(TApp.getInstance().getApplicationContext(),"mainNewFunc",mainFuncString);
                mView.showFuncs(mainNewFuncs);
                break;
            case 2:
                try {
                    ResponseBody response = (ResponseBody) data;
                    SecretKeySpec key = new SecretKeySpec(sKey.getBytes(), "AES");
                    byte[] bytes = response.bytes();
                    Logger.e("decrypt:--pre:" + new String(bytes));
                    byte[] datas = AESCrypt.decrypt(key, ivParameter.getBytes(), bytes);
                    Logger.e("decrypt-->result:" + new String(datas));
                    String result = new String(datas).trim();
                    MainContent mainContent = gson.fromJson(result, MainContent.class);
                    if (mainContent != null) {
                        if (mainContent.getHourData() != null) {
                            mView.showMainContent(mainContent);
                        } else {
                            try {
                                MainContentBean mainContentBean = gson.fromJson(result, MainContentBean.class);
                                mainContent.setAqi(mainContentBean.getAqi());
                                mainContent.setAqi_5days(mainContentBean.getAqi_5days());
                                mainContent.setAqi_hour(mainContentBean.getAqi_hour());
                                mainContent.setCityId(mainContent.getCityId());
                                mainContent.setCityName(mainContent.getCityName());
                                mainContent.setZs(mainContentBean.getZs());
                                mainContent.setSk(mainContentBean.getSk());
                                mainContent.setSk_weather(mainContentBean.getSk_weather());
                                List<MainContentBean.HourDataBean> hourDataBeans = new ArrayList<>();
                                JSONObject obj = new JSONObject(result);
                                JSONObject weaHour72 = obj.optJSONObject("weaHour72");
                                Iterator<String> it = weaHour72.keys();
                                while (it.hasNext()) {
                                    MainContentBean.HourDataBean bean = new MainContentBean.HourDataBean();
                                    String timeKey = it.next();
                                    SimpleDateFormat sdf0 = new SimpleDateFormat("HH");
                                    String hour = sdf0.format(new Date(Long.parseLong(timeKey) * 1000));
                                    JSONObject timeValue = weaHour72.optJSONObject(timeKey);
                                    bean.setTq(timeValue.optString("tq", ""));
                                    bean.setTemp(timeValue.optString("temp", "25"));
                                    bean.setHour(hour);

                                    hourDataBeans.add(bean);
                                }
                                mainContent.setHourData(hourDataBeans);
                                mView.showMainContent(mainContent);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }
                break;
            case 3:
                LocationCity city = (LocationCity) data;
                if (city != null) {
                    mView.showCityId(city.getCityid());
                }
                break;
        }
    }

    @Override
    public void onDataCallBackError(int requestId, Throwable throwable) {

    }

    @Override
    public void onDestroy() {
        if (mView != null) mView = null;
        if (mainLoader != null) mainLoader = null;
        if (cityLoader != null) cityLoader = null;
        if (newsLoader != null) newsLoader = null;
        if (funcsLoader != null) funcsLoader = null;
    }


}
